package com.zf.bm.common.validator;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONArray;
import com.zf.bm.common.utils.StringUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;

public class EnumIpValueValidator implements ConstraintValidator<EnumIpValue, Object> {
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        boolean flag = true;
        if(value instanceof JSONArray){
            flag = isFlag(value, flag);
        }
        return flag;
    }

    private static boolean isFlag(Object value, boolean flag) {
        List<String> strings = JSONArray.parseArray(value.toString(), String.class);
        a:
        for (String string : strings) {
            if (string.contains("-")) {
                List<String> strings1 = Arrays.asList(string.split("-"));
                b:
                for (String s : strings1) {
                    if (!Validator.isIpv4(s)) {
                        flag = false;
                        break a;
                    }
                }
                continue;
            }
            if (!StringUtil.match(ValidatorConst.IPV4_AND_IPV6_PATTERN, string)) {
                flag = false;
                break a;
            }

        }
        return flag;
    }
}
